//
// Created by PulsarV on 18-11-11.
//

#include <stdio.h>
#include <cstring>
#include <boost/mpi.hpp>
#include <opencv2/opencv.hpp>
#include <zconf.h>


int main(int argc, char *argv[]) {
    int rank, size, len;
    boost::mpi::environment env;
    boost::mpi::communicator world;
    if (world.rank() == 0) {
        std::cout << "world.rank():" << world.rank() << std::endl;
        cv::VideoCapture cap(0);
        std::cout << "Open Camera In Rank:" << rank << std::endl << std::endl;
        while (true) {
            cv::Mat frame;
            cap >> frame;
            cv::resize(frame, frame, cv::Size(640, 480));
            cv::imshow("master", frame);
            std::vector<uchar> send_data;
            cv::imencode(".png", frame, send_data);
            int buffer_size = 640 * 480 * 3;
            boost::mpi::request req[2];
            req[0] = world.isend(1, 0, send_data);
            std::vector<uchar> recive_data;
            req[1] = world.irecv(1, 0, recive_data);
            boost::mpi::wait_all(req, req + 2);
            if (not recive_data.empty()) {
                cv::Mat recive_image = cv::imdecode(recive_data, CV_32FC3);
                imshow("slaver caclulate", recive_image);
            }
            cv::waitKey(1);
        }
    }
    if (world.rank() == 1) {
        std::cout << "world.rank():" << world.rank() << std::endl;
        while (true) {
            boost::mpi::request req[1];
            std::vector<uchar> recive_data;
            req[0] = world.irecv(0, 0, recive_data);
            boost::mpi::wait_all(req, req + 1);
            if (not recive_data.empty()) {
                cv::Mat recive_image = cv::imdecode(recive_data, CV_32FC3);
                imshow("slaver", recive_image);
                cv::resize(recive_image, recive_image, cv::Size(640 / 2, 480 / 2));
                std::vector<uchar> send_data;
                cv::imencode(".png", recive_image, send_data);
                req[0] = world.isend(0, 0, send_data);
                boost::mpi::wait_all(req, req + 1);
            }
            cv::waitKey(1);
        }
    }
}


